package cn.xeblog.server.action.specialAc;

import java.util.HashMap;
import java.util.Map;

public class ActionCounter {
    private final Map<Integer, Integer> actionCounts = new HashMap<>();
    private final Map<Integer, Map<String, Integer>> personCounts = new HashMap<>();

    public void recordAction(Integer action, String person) {
        // 统计动作次数
        actionCounts.put(action, actionCounts.getOrDefault(action, 0) + 1);

        // 统计每个动作下每个人的次数
        if (!personCounts.containsKey(action)) {
            personCounts.put(action, new HashMap<>());
        }
        Map<String, Integer> personMap = personCounts.get(action);
        personMap.put(person, personMap.getOrDefault(person, 0) + 1);
    }

    public Integer getMostFrequentAction() {
        int maxCount = 0;
        Integer mostFrequentAction = null;
        for (Map.Entry<Integer, Integer> entry : actionCounts.entrySet()) {
            if (entry.getValue() > maxCount) {
                maxCount = entry.getValue();
                mostFrequentAction = entry.getKey();
            }
        }
        return mostFrequentAction;
    }

    public String getPersonWithMostActionsIn(Integer action) {
        if (!personCounts.containsKey(action)) {
            return null;
        }

        int maxCount = 0;
        String username = null;
        Map<String, Integer> personMap = personCounts.get(action);
        for (Map.Entry<String, Integer> entry : personMap.entrySet()) {
            if (entry.getValue() > maxCount) {
                maxCount = entry.getValue();
                username = entry.getKey();
            }
        }
        return username;
    }

    public static void main(String[] args) {
        ActionCounter counter = new ActionCounter();
        counter.recordAction(1, "P1");
        counter.recordAction(2, "P2");
        counter.recordAction(2, "P2");
        counter.recordAction(3, "P1");
        counter.recordAction(2, "P3");
        counter.recordAction(1, "P1");

        System.out.println("最频繁的动作: " + counter.getMostFrequentAction());
        System.out.println("上述动作最多的人: " + counter.getPersonWithMostActionsIn(counter.getMostFrequentAction()));
    }
}

